package com.wencai.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CmdExecutor {
    private static final String windowsFile = "D:\\Code\\Stock\\backup\\Java\\Wencai\\src\\main\\resources\\hexin-v.bundle.js";

    private static final String linuxFile = "/root/wencai/hexin-v.bundle.js";

    public static String getToken() {
        String file = getAbsPath();

        try {
            return execute("node", file).toString();
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static String getAbsPath() {
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("win")) {
            return windowsFile;
        } else{
            return linuxFile;
        }
    }

    public static Object execute(String cmd, String file, String... params) throws IOException, InterruptedException {
        int length = params.length;
        String[] cmdLines = new String[length + 2];
        cmdLines[0] = cmd;
        cmdLines[1] = file;
        System.arraycopy(params, 0, cmdLines, 2, length);
        Process process = Runtime.getRuntime().exec(cmdLines);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream())
        );
        String line;
        StringBuilder result = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        int exitCode = process.waitFor();
        if (exitCode == 0) {
            return result;
        } else {
            // 读取错误流
            BufferedReader errorReader = new BufferedReader(
                    new InputStreamReader(process.getErrorStream())
            );
            System.err.println("Error:");
            StringBuilder errLines = new StringBuilder();
            while ((line = errorReader.readLine()) != null) {
                errLines.append(line).append(System.lineSeparator());
                System.err.println(line);
            }
            throw new IOException(errLines.toString());
        }
    }
}
